package hgz.stu.review.thread.lock;
import java.util.LinkedList;
import java.util.Random;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class OptimisticLockPattern {
    public static void main(String[] args){     
         SelfQueue selfqueue = new SelfQueue();

         //创建生产者线程和消费者线程
         Thread prodThread = new Thread(new Producer(selfqueue));
         Thread consThread = new Thread(new Consumer(selfqueue));

         //启动生产者线程和消费者线程
         prodThread.start();
         consThread.start();
    }
}


class SelfQueue{
    int max = 5;
    LinkedList<Integer> ProdLine = new LinkedList<Integer>();
    Lock lock = new ReentrantLock(); 
    Condition full = lock.newCondition();  
    Condition empty = lock.newCondition();

    public void produce(int ProdRandom){       
        try {
            lock.lock();
            while(max == ProdLine.size()){
                System.out.println("存储量达到上限，请等待");
                full.await();
            }
            ProdLine.add(ProdRandom);
            empty.signal();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally{
            lock.unlock();
        }
    } 

    public int consume(){  
        int m = 0;
        try {
            lock.lock();
            while(ProdLine.size() == 0){
                System.out.println("队列是空的，请稍候");
                empty.await();
            }
            m = ProdLine.removeFirst();
            full.signal(); 
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally{
            lock.unlock();
            return m;
        }
    }
}

//生产者
class Producer implements Runnable{
    private final SelfQueue selfqueue;

    public Producer(SelfQueue selfqueue) {
          this.selfqueue = selfqueue;
    }

    public void run() {
      for (int i = 0; i < 10; i++) {
            Random random = new Random();
            int ProdRandom=random.nextInt(10);
            System.out.println("Produced: " + ProdRandom);
            selfqueue.produce(ProdRandom);          
      }
  }
}

//消费者
class Consumer implements Runnable{
    private final SelfQueue selfqueue;

    public Consumer(SelfQueue selfqueue) {
          this.selfqueue = selfqueue;
    }

    public void run() {
      while(true) {
              System.out.println("Consumed: "+ selfqueue.consume());
      }
  }
}